<template>
	<view @touchstart="touchStartFn" @touchmove="toucMoveFn" @touchend="touchEndFn"
		:style="`transform:translateX(-${moveDistance}px);transition: transform .3s;`" class="dragLeft">
		<slot></slot>
	</view>
</template>

<script>
	/*
		1.direction:方向，x表示水平，y表示垂直
		2.maxDis:移动的最大距离，px和rpx均可，不带单位按px处理(必传)
		3.show:用于只显示一个拖拽，参考商城模块的购物车，相当于手动控制拖拽显隐			
	*/
	export default {
		props: {
			direction: {
				type: String,
				default: 'x'
			},
			maxDis: {
				type: [String, Number],
				default: 100
			},
			show: {
				type: [Boolean, Number],
				default: true
			}
		},
		data() {
			return {
				startX: 0, //点击起点的x轴距离
				moveDistance: 0,
				maxDistance: 0, //最大移动距离
			}
		},
		mounted() {
			this.maxDistance = this.maxDis.includes('rpx') ? uni.upx2px(this.maxDis.replace('rpx', '')) : this
				.maxDis; //最大距离转成px
		},
		methods: {
			touchStartFn(options) { //获取初始点坐标
				let startX = options.changedTouches[0].pageX;
				this.startX = startX;
			},
			toucMoveFn(options) {
				let moveX = options.changedTouches[0].pageX;
				let diff = this.startX - moveX; //差值，大于0说明左拉 小于0说明右拉
				if (diff > 0) { //左拉
					if (diff >= this.maxDistance) { //超出了最大值
						if (this.moveDistance != this.maxDistance) { //没赋过值，优化操作
							this.moveDistance = this.maxDistance;
						}
					} else if (this.moveDistance < this.maxDistance) { //没有超出最大距离
						this.moveDistance = diff;
					}
				} else if (this.moveDistance > 0) { //右拉，只有按钮完全暴露了才能右拉
					if (-diff >= this.maxDistance) {
						if (this.moveDistance > 0) { //这里加判断是为了避免重复赋值
							this.moveDistance = 0;
						}
					} else {
						this.moveDistance = -diff;
					}
				}
			},
			touchEndFn(options) { //松手之后的操作
				let endX = options.changedTouches[0].pageX;
				let quarter = this.maxDistance / 4; //最大距离的25%
				let diff = this.startX - endX;
				if (diff > 0) { //左拉
					this.moveDistance = diff > quarter ? this.maxDistance : 0;
				} else if (this.moveDistance > 0 && (-diff) >= quarter) { //右拉
					this.moveDistance = 0;
				}
			}
		},
		watch: {
			show(newVal, oldVal) {
				if (!newVal) {
					this.moveDistance = 0;
				}
			}
		}
	}
</script>